<template>
<el-drawer :title="dialog.title" :visible.sync="dialog.visible" size="50%">
    <el-form class="drawer-form" :model="ruleForm" :rules="rules" ref="ruleForm" :inline="false" label-position="top">
        <el-form-item label="门店名称" prop="title">
            <el-input v-model="ruleForm.title" placeholder="请填写门店名称"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
            <el-input type="textarea" v-model="ruleForm.intro" placeholder="请填写门店简介"></el-input>
        </el-form-item>

        <el-form-item label="门店图片" prop="titlepic">
            <upload-picture ref="titlepicRef" v-model="ruleForm.titlepic" placeholder="1张;尺寸:1000*1000;格式:jpg,png,jpeg;大小:30M以内"></upload-picture>
        </el-form-item>

        <el-form-item label="门店视频" prop="video">
            <upload-video ref="videoRef" v-model="ruleForm.video" placeholder="1个;格式:mp4;大小:30M以内"></upload-video>
        </el-form-item>

        <el-form-item label="门店相册" prop="album">
            <upload-files ref="albumRef" v-model="ruleForm.album" placeholder="10张;尺寸:1000*1000;格式:jpg,png,jpeg;大小:30M以内"></upload-files>
        </el-form-item>

        <el-form-item label="门店标签" prop="tags">
            <el-tag size="medium" type="primary" class="tag-item" :key="tag" v-for="(tag,index) in ruleForm.tags" closable :disable-transitions="false" @close="handleTagClose(tag,index)">
                {{tag}}
            </el-tag>
            <el-input class="input-new-tag" v-if="tagInputVisible" v-model="tagInputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"></el-input>
            <el-button v-else class="button-new-tag" size="small" type="success" @click="showTagInput">新增标签</el-button>
        </el-form-item>

        <el-form-item label="联系地址" prop="address">
            <el-input v-model="ruleForm.address" placeholder="请填写门店地址"></el-input>
        </el-form-item>
        <el-form-item label="交通" prop="traffic">
            <el-input v-model="ruleForm.traffic" placeholder="请填写门店交通"></el-input>
        </el-form-item>

        <el-form-item label="经纬度" prop="coordinate">
            <el-input v-model="ruleForm.coordinate" placeholder="请选择门店位置"></el-input>
            <el-amap :center="[121.59996, 31.197646]" :zoom="12" style="height: 300px;">
                <el-amap-search-box placeholder="请输入关键字" :debounce="1000" @select="selectPoi" @choose="choosePoi"></el-amap-search-box>
            </el-amap>
        </el-form-item>

        <el-form-item label="营业时间" prop="business_hours">
            <el-input v-model="ruleForm.business_hours" placeholder="请填写门店营业时间"></el-input>
        </el-form-item>

        <el-form-item label="门店分类" prop="business_category">
            <el-checkbox-group v-model="ruleForm.business_category">
                <el-checkbox v-for="item in categories" :label="item">{{item}}</el-checkbox>
            </el-checkbox-group>
        </el-form-item>

        <el-form-item label="门店区域" prop="zone_id">
            <el-select v-model="ruleForm.zone_id" placeholder="请选择门店区域">
                <el-option v-for="item in zoneList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
            <el-input v-model="ruleForm.sort" placeholder="请填写门店排序"></el-input>
        </el-form-item>

        <el-form-item label="营业状态" prop="status">
            <el-select v-model="ruleForm.status" placeholder="">
                <el-option label="营业" :value="1"></el-option>
                <el-option label="关闭" :value="0"></el-option>
                <el-option label="歇业" :value="2"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" size="medium" @click="submit">提交</el-button>
        </el-form-item>
    </el-form>
</el-drawer>
</template>

<script>
import {
    createStoreApi,
    saveStoreApi
} from "@/api/system/dictionary/store";
import {
    getFormToken
} from "@/api/system/system";
import {getChildrenApi} from "@/api/system/dictionary/region";
import uploadFiles from '@/components/upload/files.vue';
import uploadPicture from '@/components/upload/picture.vue';
import uploadVideo from '@/components/upload/video.vue';

const ruleForm = {
    id: "",
    title: "",
    titlepic: '',
    video: "",
    album: [],
    intro: "",
    address: "",
    traffic: "",
    coordinate: "",
    sort: 0,
    status: 1,
    tags: [],
    business_hours: "",
    business_category: [],
    province_id: 801,
    city_id: 802,
    zone_id: "",
    form_token: "",
};

export default {
    components: {
        uploadFiles,
        uploadPicture,
        uploadVideo
    },
    data() {
        return {
            dialog: {
                title: "",
                visible: false,
                type: "",
            },
            zoneList: [],
             categories: [
                '婚宴',
                '会务',
                '宝宝宴',
                '中餐预定'
            ],
            ruleForm: JSON.parse(JSON.stringify(ruleForm)),
            rules: {
                title: [{
                        required: true,
                        message: "门店名称必填",
                        trigger: "blur",
                    },
                    {
                        min: 2,
                        max: 30,
                        message: "长度在 2 到 30 个字符",
                        trigger: "blur",
                    },
                ],
                titlepic: [{
                    required: true,
                    message: "请上传门店头图",
                    trigger: "blur",
                }],
                album: [{
                    required: true,
                    message: "请上传门店相册",
                    trigger: "blur",
                }],
                video: [{
                    required: true,
                    message: "请上传门店视频",
                    trigger: "blur",
                }],
                address: [{
                    required: true,
                    message: "请填写门店地址",
                    trigger: "blur",
                }],
                coordinate: [{
                        required: true,
                        message: "请填写门店经纬度",
                        trigger: "blur",
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (!value || typeof value !== 'string') {
                                callback(new Error('请填写门店经纬度'));
                            } else {
                                const parts = value.split(',').map(s => parseFloat(s));
                                if (parts.length === 2 && parts.every(n => !isNaN(n))) {
                                    callback();
                                } else {
                                    callback(new Error('请填写门店经纬度'));
                                }
                            }
                        },
                        trigger: "blur",
                    }
                ],
                tags: [{
                    required: true,
                    message: "请填写门店标签",
                    trigger: "blur",
                }],
                business_hours: [{
                    required: true,
                    message: "请填写门店营业时间",
                    trigger: "blur",
                }],
                zone_id: [{
                    required: true,
                    message: "请选择门店区域",
                    trigger: "change",
                }]
            },
            tagInputVisible: false,
            tagInputValue: '',
        };
    },
    computed: {
        markerPosition() {
            const c = this.ruleForm.coordinate;
            if (!c || typeof c !== 'string') return null;
            const parts = c.split(',').map(s => parseFloat(s));
            if (parts.length === 2 && parts.every(n => !isNaN(n))) return parts;
            return null;
        }
    },
    methods: {
        showAddView() {
            let dialog = {
                title: "添加门店",
                visible: true,
                type: "create",
            };
            this.dialog = dialog;
            // 初始化表单
            this.ruleForm = JSON.parse(JSON.stringify(ruleForm));
            this.getZoneList();
            // 获取表单的token
            getFormToken({
                api: "/api/system.source/create",
            }).then(res => {
                this.ruleForm.form_token = res.data.token;
            });
        },
        showSaveView(row) {
            let dialog = {
                title: "编辑门店",
                visible: true,
                type: "save",
            };
            this.dialog = dialog;
            // 初始化表单
            this.ruleForm = Object.assign({}, row);
            this.getZoneList();
            // 获取表单的token
            getFormToken({
                api: "/api/system.source/save",
            }).then(res => {
                this.ruleForm.form_token = res.data.token;
            });
        },
        // 获取zoneList
        getZoneList() {
            getChildrenApi({id: 802}).then((res) => {
                if (res.code == 200) {
                    this.zoneList = res.data.list;
                } else {    
                    this.$message.warning(res.msg);
                }
            });
        },

        // 移除标签
        handleTagClose(tag) {
            this.ruleForm['tags'].splice(this.ruleForm['tags'].indexOf(tag), 1);
        },
        showTagInput() {
            this.tagInputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },

        handleInputConfirm() {
            let tagInputValue = this.tagInputValue;
            if (tagInputValue) {
                this.ruleForm['tags'].push(tagInputValue);
            }
            this.tagInputVisible = false;
            this.tagInputValue = '';
        },

        selectPoi(e) {
            console.log('selectPoi: ', e);
        },

        choosePoi(e) {
            console.log('choosePoi: ', e);
        },

        submit() {
            console.log(this.ruleForm)

            this.$refs["ruleForm"].validate((valid) => {
                // 验证失败阻止提交
                if (!valid) return false;
                // 提交表单
                if (this.dialog.type == "create") {
                    createStoreApi(this.ruleForm)
                        .then((res) => {
                            if (res.code == "200") {
                                this.dialog.visible = false;
                                this.$emit("getTableData", {});
                                this.$message.success(res.msg);
                            } else {
                                this.$message.error(res.msg);
                            }
                        })
                        .catch((res) => {
                            this.$message.error(res.msg);
                        });
                } else {

                    saveStoreApi(this.ruleForm)
                        .then((res) => {
                            if (res.code == "200") {
                                this.dialog.visible = false;
                                this.$emit("getTableData", {});
                                this.$message.success(res.msg);
                            } else {
                                this.$message.error(res.msg);
                            }
                        })
                        .catch((res) => {
                            this.$message.error(res.msg);
                        });
                }
            });
        },
    },

}
</script>

<style lang="less" scoped>
.drawer-form {
    padding: 20px;

    .tag-item {
        margin-right: 6px;
    }

    .input-new-tag {
        margin-top: 6px;
    }
}

.amap-sug-result {
    z-index: 1000
}
</style>
